const service = axios.create({
  // 定义统一的请求头部
  headers: { Pragma: 'no-cache' },
  // 配置请求超时时间 默认值是 `0` (永不超时)
  // timeout: 10000,
  baseURL: window.BASEURL,
});

// 请求拦截
service.interceptors.request.use(function (config) {
  return config;
});

// 返回拦截
service.interceptors.response.use(
  function (response) {
    const data = response.data;
    if (data.code === 200) {
      try {
        data.data = $smUtil.decrypt(data.data);
      } catch (e) {}
    }
    return data;
  },
  function (error) {
    return {
      code: 500,
      msg: error.message || '网络请求异常，请稍后重试!',
      data: null,
    };
  }
);

const useLoading = function (loading, flag) {
  if (loading) Vue.isRef(loading) ? (loading.value = flag) : (loading = flag);
};

const axiosGet = function (url, data, loading) {
  useLoading(loading, true);
  return service
    .get(url, { params: Vue.unref(data) })
    .then(function (res) {
      useLoading(loading, false);
      return res;
    })
    .catch(function (err) {
      useLoading(loading, false);
      return err;
    });
};

const axiosPost = function (url, data, loading) {
  useLoading(loading, true);
  return service
    .post(url, Vue.unref(data))
    .then(function (res) {
      useLoading(loading, false);
      return res;
    })
    .catch(function (err) {
      useLoading(loading, false);
      return err;
    });
};

const axiosPut = function (url, data, loading) {
  useLoading(loading, true);
  return service
    .put(url, Vue.unref(data))
    .then(function (res) {
      useLoading(loading, false);
      return res;
    })
    .catch(function (err) {
      useLoading(loading, false);
      return err;
    });
};

const axiosDelete = function (url, data, loading) {
  useLoading(loading, true);
  return service
    .delete(url, { params: Vue.unref(data) })
    .then(function (res) {
      useLoading(loading, false);
      return res;
    })
    .catch(function (err) {
      useLoading(loading, false);
      return err;
    });
};

const axiosUpload = function (url, formdata, progress, cancel) {
  const CancelToken = axios.CancelToken;
  return service.request({
    url: url,
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    data: formdata,
    onUploadProgress: function (progressEvent) {
      progress && progress(parseInt((progressEvent.loaded / progressEvent.total) * 100));
    },
    cancelToken: new CancelToken(function executor(c) {
      cancel && cancel(c);
    }),
  });
};
